//
//  ShoppingCart_ViewController.m
//  chilemat
//
//  Created by Cristian Gonzalez Figueroa on 23-04-14.
//  Copyright (c) 2014 Chilemat SpA. All rights reserved.
//

#import "ShoppingCart_ViewController.h"
#import "classGenericCell.h"
#import "CustomCell.h"
#import "dao.h"

@interface ShoppingCart_ViewController ()

@end

@implementation ShoppingCart_ViewController

@synthesize tableViewSearch;
@synthesize dataArraySearch = _dataArraySearch;
@synthesize activeField;
@synthesize lblSubTotal, lblTotal, lblDespacho;
@synthesize viewResumeShoppingCart;
@synthesize imgEmptyCart, lblTextEmptyCart;
@synthesize json;
@synthesize jsonUpdateShoppingCart;

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"count=%lu", (unsigned long)[_dataArraySearch count]);
    return [_dataArraySearch count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault
                                 reuseIdentifier:CellIdentifier];
    }
    
    classGenericCell *objCell = [_dataArraySearch objectAtIndex:indexPath.row];

    //-----------------------------------------------------------------------------------
    //Leemos
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    //1.- Imagen normal
    NSString *strNameImageTmp = @"";
    NSString *documentsDirectory = [paths objectAtIndex:0];
    strNameImageTmp = [NSString stringWithFormat:@"3_%@.jpg", objCell.strIdProducto];
    
    NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp ];
    UIImage* image = [UIImage imageWithContentsOfFile:path];
    //-----------------------------------------------------------------------------------
    
    cell.imgImageView.image = image;
    
    cell.lblQty.text = objCell.strSKU; //*****Parche temporal
    
    //cell.imgImageView.image = [UIImage imageNamed:@"img_maletin.png"];
    cell.lblTrademark.text = objCell.strTrademark;
    cell.lblTitleLabel.text = objCell.strTitleLabel;
    cell.txtQty.text = objCell.strQty;
    cell.txtQty.tag = [objCell.strIdProducto integerValue];  //Id del producto
    
    cell.lblPrice.text = objCell.strPrice;

    cell.btnProduct.tag = indexPath.row; //Id del producto para poder actualizarlo o eliminarlo
    cell.btnDeleteProduct.tag = [objCell.strIdProducto integerValue];  //Id del producto para poder actualizarlo o eliminarlo
    cell.btnDeleteProduct.titleLabel.text = [NSString stringWithFormat:@"%li", (long)indexPath.row];
    cell.btnDeleteProduct.titleLabel.textColor = [UIColor clearColor];
    
    UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
    numberToolbar.barStyle = UIBarStyleDefault;
    
    numberToolbar.items = [NSArray arrayWithObjects:
                           [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(cancelNumberPad) ],
                           [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                           [[UIBarButtonItem alloc]initWithTitle:@"Ok" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad:)],
                           nil];

    [numberToolbar sizeToFit];

    cell.txtQty.inputAccessoryView = numberToolbar;
    
    return cell;
}

-(void)cancelNumberPad{
    
    activeField = nil;
    
    [self.view endEditing:YES];
}

- (void)doneWithNumberPad:(id)sender {
    
    activeField = nil;
    
    [self.view endEditing:YES];
}

-(NSString*) formatCurrencyValue:(double)value
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [numberFormatter setCurrencySymbol:@"$"];
    [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSNumber *c = [NSNumber numberWithFloat:value];
    return [numberFormatter stringFromNumber:c];
}

- (void) retrieveDataSearch{
    
    [_dataArraySearch removeAllObjects];
    _dataArraySearch = [[NSMutableArray alloc] init];

    dao *objDAO = [[dao alloc] init];
    int intIdUser = [objDAO obtainCurrentIdUser];
    NSMutableArray *ArrayProducts;
    NSArray *ArrayProduct;

    ArrayProducts = [objDAO obtainProductsShoppingCart:intIdUser];
    
    for (int i = 0; i<ArrayProducts.count; i++)
    {
        ArrayProduct = ArrayProducts[i];
/*
 strIdUsuario           = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,0 )];
 strIdProducto          = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,1 )];
 strIdSKU               = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,2 )];
 strDescripcionProd     = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,3 )];
 strIdMarca             = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,4 )];
 strDescripcionMarca    = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,5 )];
 strCantidad            = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,6 )];
 strNeto                = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,7 )];
 strIva                 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,8 )];
 strTotal               = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,9 )];
*/

        NSString *strTitleLabel = ArrayProduct[3]; //@"Cartera Desigual Fucsia, ideal para paseos livianos y comodos en todo clima. De textura liviana, materiales finos.";
        NSString *strSubtitleLabel = @"";
        NSString *strTrademark = ArrayProduct[5]; //@"DESIGUAL";
        NSString *strIdmark = ArrayProduct[4];
        
        NSString *strSKU = ArrayProduct[2];
        NSString *strIdProducto = ArrayProduct[1];
        NSString *strReviews = @"";
        NSString *strPrice = [NSString stringWithFormat:@"%@",  [self formatCurrencyValue:[ArrayProduct[9] doubleValue]]  ]; //@"$ 26.580 c/u";
        NSString *strOfferPrice = @"";
        NSString *strPriceDuplicated = @"";
        NSString *strDiscount = @"";
        NSString *strOfferTime = @"";
        
        NSString *strCantidadTmp = [NSString stringWithFormat:@"%.0f", [ArrayProduct[6] floatValue] ];   //%.2f
        
        NSString *strQty = strCantidadTmp;
        
        classGenericCell *objCell = [[classGenericCell alloc] initClassCell:strTitleLabel andSubtitleLabel:strSubtitleLabel andTrademark:strTrademark andIdMark:strIdmark andSKU:strSKU andStrIdProducto:strIdProducto andReviews:strReviews andstrPrice:strPrice andOfferPrice:strOfferPrice andstrPriceDuplicated:strPriceDuplicated andDiscount:strDiscount andOfferTime:strOfferTime andQty:strQty];
        
        [_dataArraySearch addObject:objCell];
    }
    
    [self.tableViewSearch reloadData];
//------------------------------------------

    if (ArrayProducts.count > 0) { //Si existen productos busco los totales.

        NSArray *ArrayResumeShoppingCart;
        
        ArrayResumeShoppingCart = [objDAO obtainResumeShoppingCart:intIdUser];
        
        if (ArrayResumeShoppingCart.count > 0) {
            
            NSLog(@"strTotal =%i", [ArrayResumeShoppingCart[0] intValue] );
            NSLog(@"strCantidadTotal =%i", [ArrayResumeShoppingCart[1] intValue] );
            
            lblSubTotal.text = [NSString stringWithFormat:@"%@",  [self formatCurrencyValue:[ArrayResumeShoppingCart[0] doubleValue]]  ];
            //  lblDespacho.text = @"";
            lblTotal.text = [NSString stringWithFormat:@"%@",  [self formatCurrencyValue:[ArrayResumeShoppingCart[0] doubleValue]]  ];
        }
        else{
            
            lblSubTotal.text = @"0";
            lblDespacho.text = @"0";
            lblTotal.text = @"0";
        }
    }else{
        viewResumeShoppingCart.hidden = YES;
        tableViewSearch.hidden = YES;
        
        imgEmptyCart.hidden = NO;
        lblTextEmptyCart.hidden = NO;
    }
}

- (void)showTabBar {
    
    UITabBar *tabBar = self.tabBarController.tabBar;
    UIView *parent = tabBar.superview; // UILayoutContainerView
    UIView *content = [parent.subviews objectAtIndex:0];  // UITransitionView
    UIView *window = parent.superview;
    
    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect tabFrame = tabBar.frame;
                         tabFrame.origin.y = CGRectGetMaxY(window.bounds) - CGRectGetHeight(tabBar.frame);
                         tabBar.frame = tabFrame;
                         
                         CGRect contentFrame = content.frame;
                         contentFrame.size.height -= tabFrame.size.height;
                     }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    dao *objDAO = [[dao alloc] init];
    int intIdUsuario = [objDAO obtainCurrentIdUser];
    
    NSLog(@"intIdUsuario =%i", intIdUsuario);
    
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"iphone_header.png"] forBarMetrics:UIBarMetricsDefault];
/*
    UIImage *tabBarBackGroudImage;
    tabBarBackGroudImage = [UIImage imageNamed:@"tab_carro.png"];
    [self.tabBarController.tabBar setBackgroundImage:tabBarBackGroudImage];
*/
    
    [self retrieveDataSearch];

    [self showTabBar];
    
    [self loadTabbar];
}

- (void) loadTabbar{
    //-------------------------------------------------------------------------------------
    dao *objDAO = [[dao alloc] init];
    int intIdUsuario = [objDAO obtainCurrentIdUser];
    
    if (intIdUsuario == -1) {
        intIdUsuario = 1;
    }
    
    NSArray *ArrayResumeShoppingCart;
    NSString *strTotalCarro = @"0";
    
    
    ArrayResumeShoppingCart = [objDAO obtainResumeShoppingCart:intIdUsuario];
    
    if (ArrayResumeShoppingCart.count > 0) {
        
        NSLog(@"strTotal =%i", [ArrayResumeShoppingCart[0] intValue] );
        NSLog(@"strCantidadTotal =%i", [ArrayResumeShoppingCart[1] intValue] );
        
        strTotalCarro = ArrayResumeShoppingCart[1];
    }
    
    //----------------------------------
    UITabBar *tabBar = self.tabBarController.tabBar; //tabBarController.tabBar;
    UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
    UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];
    UITabBarItem *tabBarItem3 = [tabBar.items objectAtIndex:2];
    UITabBarItem *tabBarItem4 = [tabBar.items objectAtIndex:3];
    UITabBarItem *tabBarItem5 = [tabBar.items objectAtIndex:4];
    
    tabBarItem1.selectedImage = [[UIImage imageNamed:@"icon_inicio_activo.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem1.image = [[UIImage imageNamed:@"icon_inicio.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem1.title = @"Inicio";
    
    tabBarItem2.selectedImage = [[UIImage imageNamed:@"icon_buscar_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem2.image = [[UIImage imageNamed:@"icon_buscar.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem2.title = @"Buscar";
    
    tabBarItem3.selectedImage = [[UIImage imageNamed:@"icon_carro_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem3.image = [[UIImage imageNamed:@"icon_carro.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem3.title = @"Carro";
    tabBarItem3.badgeValue = strTotalCarro;
    
    tabBarItem4.selectedImage = [[UIImage imageNamed:@"icon_cuenta_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem4.image = [[UIImage imageNamed:@"icon_cuenta.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem4.title = @"Cuenta";
    
    tabBarItem5.selectedImage = [[UIImage imageNamed:@"icon_chat_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem5.image = [[UIImage imageNamed:@"icon_chat.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem5.title = @"Chat";
    //----------------------------------
}

-(void) touchesBegan :(NSSet *) touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    
    [super touchesBegan:touches withEvent:event ];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
//  [objTextSearch resignFirstResponder];
    NSLog(@"Test 1");
    
    return YES;
}

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
    UIEdgeInsets contentInsets;
    
//--------------------
    CGSize result = [[UIScreen mainScreen] bounds].size;
    if(result.height == 480)
    {
        contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height+40, 0.0);
    }
    else if(result.height == 568)
    {
        contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    }
//--------------------
    
    tableViewSearch.contentInset = contentInsets;
    tableViewSearch.scrollIndicatorInsets = contentInsets;
    
    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your app might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    
    if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {

        [self.tableViewSearch scrollRectToVisible:activeField.frame animated:YES];
        
    }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    tableViewSearch.contentInset = contentInsets;
    tableViewSearch.scrollIndicatorInsets = contentInsets;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

//-----------------------------------------------------
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(keyboardWillBeHidden:)
//                                                 name:UIKeyboardWillHideNotification object:nil];
//-----------------------------------------------------
    
    self.tableViewSearch.dataSource = self;
    self.tableViewSearch.delegate = self;

    [self retrieveDataSearch];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)backToProduct:(id)sender {

    dao *objDAO = [[dao alloc] init];
    
    if ([objDAO obtainProductBack] == 0) {
        //Back desde el home
        [self.navigationController popToRootViewControllerAnimated:YES];
//      [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
    }else{
        //Back desde la busqueda
        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:2] animated:YES];
    }
}

- (IBAction)callNumber:(id)sender {

    NSString *strContactPhone;
    
    dao *objDAO = [[dao alloc] init];
    
    strContactPhone = [NSString stringWithFormat:@"tel://%@", [objDAO obtainCallCenterNumber]];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strContactPhone]];
}

-(void) deleteProductShoppingCartCloud:(int) intIdUsuario  intIdProducto: (int) intIdProducto{

    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonCarroCompra.aspx?strJsonBase=JsonBorraProductoCarro&strIdUsuario=%i&strIdProducto=%i", intIdUsuario, intIdProducto];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Delete product shoping cart perfecto");
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }
     }];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != 0)
    {
        dao *objDAO = [[dao alloc] init];
        
        int intIdUsuario = [objDAO obtainCurrentIdUser];
        int intIdProducto = [objDAO obtainCurrentProduct];

        if (intIdUsuario <= 1) {
            [self crearUsrCloud];

            UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @""
                                                           message: @"Un error interno a ocurrido, intente nuevamente."
                                                          delegate: self
                                                 cancelButtonTitle:@"Seguir comprando"
                                                 otherButtonTitles:@"Ir al carrito",nil];
            [alert show];
            
        }else{
            //No es tan gravitante la caída de HTTP de esta consulta al cloud
            [self deleteProductShoppingCartCloud:intIdUsuario intIdProducto: intIdProducto];
            
            [objDAO deleteProductShoppingCart:intIdUsuario intIdProducto:intIdProducto];
            
            [self retrieveDataSearch];
            [self loadTabbar];
        }
        
    }else{
        
        NSLog(@"Nothing");
    }
}

- (IBAction)deleteProductCart:(id)sender {
    
    UIButton  *btnDeleteProduct = sender;
    
    dao *objDAO = [[dao alloc] init];
    int intIdProducto = (int) btnDeleteProduct.tag;

    [objDAO deleteCurrentProduct];
    [objDAO insertCurrentProduct:intIdProducto];
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @""
                                                   message: @"¿Desea eliminar el producto del carro?"
                                                  delegate: self
                                         cancelButtonTitle:@"Cancelar"
                                         otherButtonTitles:@"Eliminar producto",nil];
    [alert show];
}

- (NSString *)stringByRemovingControlCharacters: (NSString *)inputString
{
    NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];
    NSRange range = [inputString rangeOfCharacterFromSet:controlChars];
    if (range.location != NSNotFound) {
        NSMutableString *mutable = [NSMutableString stringWithString:inputString];
        while (range.location != NSNotFound) {
            [mutable deleteCharactersInRange:range];
            range = [mutable rangeOfCharacterFromSet:controlChars];
        }
        return mutable;
    }
    return inputString;
}

-(void) crearUsrCloud{
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonRegistraUsuario.aspx?strJsonBase=JsonUsuarioIns"];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Crear Usuario perfecto");
             
             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
             
             //[{"usr":"21"}]
             
             json = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
             
             int intIdUsuario = [  [[json objectAtIndex:0] objectForKey:@"usr"] intValue];
             
             NSLog(@"intIdUsuario =%i", intIdUsuario);
             
             dao *objDAO = [[dao alloc] init];
             
             [objDAO deleteCurrentIdUser];
             [objDAO insertCurrentIdUser:intIdUsuario];
             
             //strSocialLoginId = 3 //Correo
             [objDAO deleteUserSistem:intIdUsuario];
             
             int intRetorno = [objDAO insertUserSistem:intIdUsuario strUser:@"" strPassword:@"" strSocialLoginId:@"3" strEmail:@""];
             
             NSLog(@"intRetorno =%i", intRetorno);
             
             
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }
     }];
    
}

-(bool) updateShoppingCartCloud:(int) intIdUsuario intIdProducto:(int) intIdProducto dblCantidad:(float) dblCantidad{
    
    //Create or Product Shopping Cart
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonCarroCompra.aspx?strJsonBase=JsonInsUpd&strIdUsuario=%i&strIdProducto=%i&strCantidad=%.2f", intIdUsuario, intIdProducto, dblCantidad];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    NSURLResponse * response = nil;
    NSError * error = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                          returningResponse:&response
                                                      error:&error];
    if (error == nil)
    {
        jsonUpdateShoppingCart = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        
        int intIdResumenCarroCompra = 0;
        
        intIdResumenCarroCompra = [ [[jsonUpdateShoppingCart objectAtIndex:0] objectForKey:@"intIdResumenCarroCompra"] intValue];
        
        return YES;
    }else{
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @""
                                                       message: @"Error remoto al actualizar el carro, intente nuevamente."
                                                      delegate: self
                                             cancelButtonTitle:@"Seguir comprando"
                                             otherButtonTitles:@"Ir al carrito",nil];
        [alert show];
        
        NSLog(@"Error");
        return NO;
    }
}


- (IBAction)updateCartQty:(id)sender {

    UITextField *txtCantidad;
    
    txtCantidad = sender;
    
    NSLog(@"txtCantidad.text =%@", txtCantidad.text);
    NSLog(@"intIdProducto =%li", (long)txtCantidad.tag);  //Id del producto
    
//----------------------------------------------------------------------------------------
    dao *objDAO = [[dao alloc] init];
    int intIdProducto = (int ) txtCantidad.tag;
    int intIdUsuario = 0;
    int intReturn = 0;
    float dblCantidad = [txtCantidad.text floatValue];
    
    intIdUsuario = [objDAO obtainCurrentIdUser];
    
    if (intIdUsuario <= 1) {
        
        [self crearUsrCloud];
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @""
                                                       message: @"Un error interno a ocurrido, intente nuevamente."
                                                      delegate: self
                                             cancelButtonTitle:@"Seguir comprando"
                                             otherButtonTitles:@"Ir al carrito",nil];
        [alert show];

    }else{
        //1.- Actualizamos en Amazon
        intIdUsuario = [objDAO obtainCurrentIdUser];
        
        //1.- Actualizamos en Amazon
        
        bool blnReturnCloud = [self updateShoppingCartCloud:intIdUsuario intIdProducto:intIdProducto dblCantidad:dblCantidad];
        
        if (blnReturnCloud) {
            
            //2.- Actualizamos localmente
            intReturn = [objDAO updateProductQtyShoppingCart:intIdUsuario intIdProducto:intIdProducto dblCantidad:dblCantidad ];
            
            [self retrieveDataSearch];
        }
        
    }

//----------------------------------------------------------------------------------------
    
//1.- Con el Id de producto y la cantidad, actualizar el detalle del carro y el encabezado en sQlLite
//2.- Luego obtener los nuevos valores y refrescar los label de la ventana

}

- (IBAction)editQtyProduct:(id)sender {

    activeField = sender;
}

- (IBAction)gotoCheckOut:(id)sender {
/*
1.- Determinar si el usuario ya tiene una sesión de login en curso.
*/
    NSInteger intActiveLogin = 0; //0 = Inactivo, 1 = Activo
    
    //intActiveLogin = 1;
    
    if (intActiveLogin == 0) {

        [self performSegueWithIdentifier:@"segueLogin" sender:nil];

    }else{

        [self performSegueWithIdentifier:@"segueDespacho" sender:nil];
    }
    
}


@end












